﻿<%@ Page Title="Promotion Engine -  Promotion Item Point" Language="C#" MasterPageFile="~/PromotionPage.Master" AutoEventWireup="true"
    CodeBehind="PromotionItemPoint.aspx.cs" Inherits="PromotionEngine.PromotionItemPoint" %>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPromotionPage" runat="server">
    <script type="text/javascript">
        var oPromotionItem = {};
        var oReferenceValueItemSourceType;
        var oReferenceValueBasedType;
        var isInsert = false;
        var sourceItemProperty;
        var gird;
        var editRowIndex;
        function itemSourceTypeDropDownEditor(container, options) {
            $('<input required data-text-field="ReferenceName" data-value-field="ReferenceValue" ID="ReferenceValueItemSource" data-bind="value:' + options.field + '"/>')
                        .appendTo(container)
                        .kendoDropDownList({
                            autoBind: false,
                            filter: "contains",
                            suggest: true,
                            optionLabel: "[Select Source Type]",
                            dataSource: oReferenceValueItemSourceType,
                            change: function (e) {
                                var cmb = this;
                                // selectedIndex of -1 indicates custom value
                                if (cmb.selectedIndex < 0 && !viewModel.allowCustomValues) {
                                    cmb.value(null); // or set to the first item in combobox
                                }
                                else {
                                    var items = $("#gridItemPoint").data("kendoGrid").dataSource.data();
                                    var item = items[editRowIndex];
                                    item.set('SourceValueName', '')
                                    item.set('SourceValue', '')
                                }
                            }
                        });
        }
        function basedTypeDropDownEditor(container, options) {
            $('<input required data-text-field="ReferenceName" data-value-field="ReferenceValue" ID="ReferenceValueBased" data-bind="value:' + options.field + '"/>')
                        .appendTo(container)
                        .kendoDropDownList({
                            autoBind: false,
                            filter: "contains",
                            suggest: true,
                            optionLabel: "[Select Based Type]",
                            dataSource: oReferenceValueBasedType
                        });
        }
        function sourceValueDropDownEditor(container, options) {
            $('<input disabled placeholder="Select Source Value" style="width:90%;" name="SourceValueName" class="k-input k-textbox" type="text" data-bind="value:' + options.field + '"/>').appendTo(container);
            $('<span class="k-icon k-i-search" style="margin-left:8px;width:16px;cursor: pointer;" onclick="OpenSourceValue()" title="Choose value" ></span>').appendTo(container);
            $('<span class="k-invalid-msg" data-for="SourceValueName"></span>').appendTo(container);
        }
        function OpenSourceValue() {
            var rowData = $('#gridItemPoint').data().kendoGrid.dataSource.data()[editRowIndex];
            if (rowData != null) {
                $("#sourceValueList").empty();
                var url = "";
                var title = "";
                //Customer
                if (rowData.SourceType == "1") {
                    url = "ItemList.aspx";
                    title = "List of Items";
                }
                //Property
                else if (rowData.SourceType == "2") {
                    url = "PropertySelectedList.aspx?PropertyType=item";
                    title = "List of Item Property";
                }
                //Query string
                else if (rowData.SourceType == "3") {
                    url = "BuildingQuery.aspx?Query=" + rowData.SourceValueName;
                    title = "Building Query String";
                }
                if (url.length > 0) {
                    var wnd = $("#sourceValueList")
                        .kendoWindow({
                            title: title,
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 1000,
                            height: 550,
                            content: { type: "POST", url: url, data: {} },
                            iframe: true
                        }).data("kendoWindow");
                    wnd.setOptions({
                        title: title
                    });
                    wnd.center().open();
                }
            }
        }
        //Get reference
        function GetReferenceItemSourceType() {
            $.ajax({
                type: "GET",
                url: "PromotionItemPoint.aspx/GetAllReferenceValueItemSourceType",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    oReferenceValueItemSourceType = $.parseJSON(response.d);
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function GetReferenceBasedType() {
            $.ajax({
                type: "GET",
                url: "PromotionItemPoint.aspx/GetAllReferenceValueBasedType",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    oReferenceValueBasedType = $.parseJSON(response.d);
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }
        function ChooseItem(itemID, itemCode, itemName, basePrice) {
            var rowData = $('#gridItemPoint').data().kendoGrid.dataSource.data()[editRowIndex];
            rowData.set('SourceValueName', itemName)
            rowData.set('SourceValue', itemID);
            $("#sourceValueList").data("kendoWindow").close();
        }
        function ChooseProperty(propertyDetailID, propertyDetailName) {
            var rowData = $('#gridItemPoint').data().kendoGrid.dataSource.data()[editRowIndex];
            rowData.set('SourceValueName', propertyDetailName)
            rowData.set('SourceValue', propertyDetailID);
            $("#sourceValueList").data("kendoWindow").close();
        }
        function ChooseQuery(Query) {
            var rowData = $('#gridItemPoint').data().kendoGrid.dataSource.data()[editRowIndex];
            rowData.set('SourceValueName', Query)
            $("#sourceValueList").data("kendoWindow").close();
        }

        $(document).ready(function () {
            
            GetReferenceBasedType();
            GetReferenceItemSourceType();
            var promotionID = $('#<%=lblPromotionID.ClientID%>').val();
            var promotionCode = $('#<%=lblPromotionCode.ClientID%>').text();
            var promotionName = $('#<%=lblPromotionName.ClientID%>').text();
            $("#MasterPromotionCode").val(promotionCode);
            $("#MasterPromotionName").val(promotionName);
            $("#MasterPromotionID").val(promotionID);
            gird = $("#gridItemPoint").kendoGrid({
                dataSource: {
                    transport: {
                        read: {
                            type: "GET",
                            url: "PromotionItemPoint.aspx/GetItemPoint",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json"
                        },
                        destroy: {
                            type: "GET",
                            url: "PromotionItemPoint.aspx/DeleteItemPoint",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json"
                        },
                        parameterMap: function (data, operation) {
                            if (operation === "read") {
                                return { promotionID: promotionID };
                            }
                            if (operation === "destroy") {
                                return { lineID: data.LineID };
                            }
                        },
                        error: function (a) {
                        },
                        serverPaging: true,
                        serverSorting: true,
                        serverFiltering: true
                    },
                    type: "odata", //Important!!!!
                    schema: {
                        data: function (a) {
                            if (a.d != null) {
                                var data = a.d.Data;
                                return data;
                            }
                        },
                        total: "d.Count",
                        model: {
                            id: "LineID",
                            fields: {
                                LineID: { type: "number" },
                                PromotionID: { type: "string" },
                                SourceType: { type: "string", validation: { required: true} },
                                SourceValue: { type: "string" },
                                GetPoint: { type: "number", validation: { required: true} },
                                BasedType: { type: "number", validation: { required: true} },
                                BasedValue: { type: "number", validation: { required: true} },
                                ItemSourceTypeName: { type: "string" },
                                BasedTypeName: { type: "string" },
                                SourceValueName: { type: "string" }
                            }
                        }
                    }
                },

                sortable: true,
                pageable: {
                    pageSize: 20,
                    refresh: true
                },
                filterable: true,
                reorderable: true,
                resizable: true,
                height: 370,
                selectable: "row",
                toolbar: [{ name: 'create', text: 'Add New' }, { name: 'excel'}],
                excel: {
                    fileName: "Promotion Item Buy.xlsx",
                    filterable: true
                },
                batch: true,
                columns: [
                            { field: "LineID", title: "Property ID", width: 300, hidden: true },
                            { field: "PromotionID", title: "Property ID", width: 300, hidden: true },
                            { field: "ItemSourceTypeName", title: "ItemSourceTypeName", width: 200, hidden: true },
                            { field: "SourceType", title: "Source Type", width: 200, editor: itemSourceTypeDropDownEditor, template: "#=ItemSourceTypeName#" },
                            { field: "SourceValue", title: "Source Value", width: 300, hidden: true },
                         { field: "SourceValueName", title: "SourceValueName", width: 300, editor: sourceValueDropDownEditor, template: "#=SourceValueName#" },
                            { field: "GetPoint", title: "Get Point", width: 120 },
                            { field: "BasedType", title: "Based Type", width: 200, editor: basedTypeDropDownEditor, template: "#=BasedTypeName#" },
                            { field: "BasedValue", title: "Based Value", width: 150 },
                            { field: "BasedTypeName", title: "DiscountTypeName", hidden: true },
                            { command: ["edit", "destroy"], title: "Action", width: "200px" }
                            ],
                editable: {
                    mode: "inline",
                    confirmation: "Are you sure you want to remove this data?"
                },
                edit: function (e) {
                    if (e.model.isNew()) {
                        isInsert = true;
                        $("a.k-grid-update")[0].innerHTML = "<span class='k-icon k-update'></span>Save";
                        e.model.set("BasedType", 1);
                        $('#ReferenceValueBased').data("kendoDropDownList").value(1);
                    }
                    else {
                        isInsert = false;
                    }
                },
                dataBound: onDataBound,
                save: function (e) {
                    
                    var listTextBox = $("input:text");
                    for (var i = 0; i < listTextBox.length; i++) {
                        var name = listTextBox[i].name;
                        if (name.length > 0) {
                            oPromotionItem[name] = $("[name=" + name + "]").val();
                        }
                    }
                    var listCheckBox = $("input:checkbox");
                    for (var i = 0; i < listCheckBox.length; i++) {
                        var name = listCheckBox[i].name;
                        if (name.length > 0) {
                            oPromotionItem[name] = $("[name=" + name + "]").prop('checked');
                        }
                    }
                    oPromotionItem.PromotionID = promotionID;
                    oPromotionItem.SourceType = $('#ReferenceValueItemSource').data("kendoDropDownList").value();
                    oPromotionItem.BasedType = $('#ReferenceValueBased').data("kendoDropDownList").value();
                    if ($.trim(oPromotionItem.SourceValueName) == '') {
                        
                        setMasterMessage("Please select Source Value.", "error");
                        return;
                    }
                    //Update or Insert Company
                    $.ajax({
                        type: "POST",
                        url: "PromotionItemPoint.aspx/UpdateItemPoint",
                        data: JSON.stringify({
                            oPromotionItem: JSON.stringify(oPromotionItem),
                            isInsert: isInsert
                        }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            gird.dataSource.read();
                            isInsert = false;
                            
                            setMasterMessage("Operation complete successful!", "success");
                        },
                        error: function (xhr, status, err) {
                            var err = eval("(" + xhr.responseText + ")");
                            alert(err.Message);
                        }
                    });
                    this.refresh();
                }
            }).data("kendoGrid");
        });
        function onDataBound(e) {
            var grid = $("#gridItemPoint").data("kendoGrid");
            $(grid.tbody).on("click", "td", function (e) {
                var row = $(this).closest("tr");
                editRowIndex = $("tr", grid.tbody).index(row);
                var colIdx = $("td", row).index(this);
            });
            $(grid.tbody).on("blur", "td", function (e) {
                var row = $(this).closest("tr");
                var rowIdx = $("tr", grid.tbody).index(row);
                var colIdx = $("td", row).index(this);
                var colName = $('#gridItemPoint').find('th').eq(colIdx).text();
                var columnField = $('#gridItemPoint').find("th").eq(colIdx).attr("data-field");
                var rowData = $('#gridItemPoint').data().kendoGrid.dataSource.data()[rowIdx];
                if (columnField == 'SourceType') {
                    //TO DO
                }
            });
        }
    </script>
      <h3>
        &nbsp;Item <span class="k-icon k-i-arrowhead-e"></span>Point
    </h3>
    <h2 style="display: none;">
        Promotion:&nbsp;
        <asp:Label ID="lblPromotionCode" runat="server"></asp:Label>
        -
        <asp:Label ID="lblPromotionName" runat="server"></asp:Label>
        <asp:HiddenField ID="lblPromotionID" runat="server"></asp:HiddenField>
    </h2>
    <div id="sourceValueList">
    </div>
    <div id="gridItemPoint">
    </div>
</asp:Content>
